#!/bin/bash
# Docker入口脚本
# 支持灵活的启动配置和初始化

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_debug() {
    if [ "${MONITOR_DEBUG:-false}" = "true" ]; then
        echo -e "${BLUE}[DEBUG]${NC} $1"
    fi
}

# 显示启动信息
show_banner() {
    echo -e "${BLUE}"
    echo "=================================================="
    echo "    通用服务器监控系统 (Universal Server Monitor)"
    echo "=================================================="
    echo -e "${NC}"
    echo "版本: 1.0.0"
    echo "启动时间: $(date)"
    echo "容器ID: $(hostname)"
    echo ""
}

# 检查环境变量
check_environment() {
    log_info "检查环境变量配置..."
    
    # 检查必需的环境变量
    local required_vars=()
    local missing_vars=()
    
    for var in "${required_vars[@]}"; do
        if [ -z "${!var}" ]; then
            missing_vars+=("$var")
        fi
    done
    
    if [ ${#missing_vars[@]} -gt 0 ]; then
        log_error "缺少必需的环境变量:"
        for var in "${missing_vars[@]}"; do
            echo "  - $var"
        done
        exit 1
    fi
    
    # 显示关键配置
    log_info "当前配置:"
    echo "  监控模式: ${MONITOR_MODE:-server}"
    echo "  检查间隔: ${MONITOR_SERVER_CHECK_INTERVAL:-300}秒"
    echo "  CPU阈值: ${MONITOR_CPU_THRESHOLD:-80.0}%"
    echo "  内存阈值: ${MONITOR_MEMORY_THRESHOLD:-85.0}%"
    echo "  磁盘阈值: ${MONITOR_DISK_THRESHOLD:-90.0}%"
    echo "  邮件通知: ${MONITOR_EMAIL_ENABLED:-false}"
    echo "  Web界面: ${MONITOR_WEB_ENABLED:-false}"
    echo "  日志级别: ${MONITOR_LOG_LEVEL:-INFO}"
}

# 创建必要的目录
create_directories() {
    log_info "创建必要的目录..."
    
    local dirs=(
        "/app/logs"
        "/app/data"
        "/app/config"
        "/app/temp"
    )
    
    for dir in "${dirs[@]}"; do
        if [ ! -d "$dir" ]; then
            mkdir -p "$dir"
            log_debug "创建目录: $dir"
        fi
    done
    
    # 设置权限
    chmod 755 /app/logs /app/data /app/temp
}

# 生成配置文件
generate_config() {
    local config_file="/app/config/monitor.json"
    
    if [ ! -f "$config_file" ]; then
        log_info "生成默认配置文件..."
        
        cat > "$config_file" << EOF
{
  "email": {
    "enabled": ${MONITOR_EMAIL_ENABLED:-false},
    "smtp_server": "${MONITOR_SMTP_SERVER:-smtp.gmail.com}",
    "smtp_port": ${MONITOR_SMTP_PORT:-587},
    "use_tls": ${MONITOR_SMTP_USE_TLS:-true},
    "username": "${MONITOR_SMTP_USERNAME:-}",
    "password": "${MONITOR_SMTP_PASSWORD:-}",
    "sender": "${MONITOR_EMAIL_SENDER:-}",
    "recipients": [${MONITOR_EMAIL_RECIPIENTS:-}]
  },
  "monitoring": {
    "server_monitor": {
      "enabled": true,
      "check_interval": ${MONITOR_SERVER_CHECK_INTERVAL:-300},
      "cpu_threshold": ${MONITOR_CPU_THRESHOLD:-80.0},
      "memory_threshold": ${MONITOR_MEMORY_THRESHOLD:-85.0},
      "disk_threshold": ${MONITOR_DISK_THRESHOLD:-90.0},
      "network_threshold": ${MONITOR_NETWORK_THRESHOLD:-100.0},
      "process_count_threshold": ${MONITOR_PROCESS_COUNT_THRESHOLD:-500}
    },
    "memory_monitor": {
      "enabled": true,
      "check_interval": ${MONITOR_MEMORY_CHECK_INTERVAL:-30},
      "warning_threshold": ${MONITOR_MEMORY_WARNING_THRESHOLD:-75.0},
      "critical_threshold": ${MONITOR_MEMORY_CRITICAL_THRESHOLD:-85.0},
      "auto_cleanup": ${MONITOR_MEMORY_AUTO_CLEANUP:-true}
    }
  },
  "web": {
    "enabled": ${MONITOR_WEB_ENABLED:-false},
    "host": "${MONITOR_WEB_HOST:-0.0.0.0}",
    "port": ${MONITOR_WEB_PORT:-8080},
    "debug": ${MONITOR_WEB_DEBUG:-false}
  },
  "logging": {
    "level": "${MONITOR_LOG_LEVEL:-INFO}",
    "file": "${MONITOR_LOG_FILE:-logs/monitor.log}",
    "max_size_mb": ${MONITOR_LOG_MAX_SIZE_MB:-10},
    "backup_count": ${MONITOR_LOG_BACKUP_COUNT:-5}
  },
  "database": {
    "enabled": ${MONITOR_DB_ENABLED:-false},
    "type": "${MONITOR_DB_TYPE:-sqlite}",
    "host": "${MONITOR_DB_HOST:-localhost}",
    "port": ${MONITOR_DB_PORT:-3306},
    "name": "${MONITOR_DB_NAME:-monitor.db}",
    "username": "${MONITOR_DB_USERNAME:-}",
    "password": "${MONITOR_DB_PASSWORD:-}"
  }
}
EOF
        log_debug "配置文件已生成: $config_file"
    else
        log_info "使用现有配置文件: $config_file"
    fi
}

# 检查系统依赖
check_dependencies() {
    log_info "检查系统依赖..."
    
    # 检查Python模块
    local python_modules=("psutil" "schedule" "requests")
    
    for module in "${python_modules[@]}"; do
        if ! python -c "import $module" 2>/dev/null; then
            log_error "Python模块 $module 未安装"
            exit 1
        fi
    done
    
    # 检查系统文件
    local system_files=("/proc/stat" "/proc/meminfo" "/proc/loadavg")
    
    for file in "${system_files[@]}"; do
        if [ ! -r "$file" ]; then
            log_warn "无法读取系统文件: $file"
        fi
    done
}

# 等待依赖服务
wait_for_services() {
    if [ "${MONITOR_DB_ENABLED:-false}" = "true" ]; then
        log_info "等待数据库服务..."
        
        local db_host="${MONITOR_DB_HOST:-localhost}"
        local db_port="${MONITOR_DB_PORT:-3306}"
        local max_attempts=30
        local attempt=1
        
        while [ $attempt -le $max_attempts ]; do
            if nc -z "$db_host" "$db_port" 2>/dev/null; then
                log_info "数据库服务已就绪"
                break
            fi
            
            log_debug "等待数据库服务... ($attempt/$max_attempts)"
            sleep 2
            ((attempt++))
        done
        
        if [ $attempt -gt $max_attempts ]; then
            log_error "数据库服务连接超时"
            exit 1
        fi
    fi
}

# 运行健康检查
health_check() {
    log_info "执行健康检查..."
    
    # 检查Python进程
    if ! python -c "import psutil; psutil.cpu_percent()" 2>/dev/null; then
        log_error "健康检查失败: 无法获取系统信息"
        return 1
    fi
    
    # 检查配置文件
    if [ ! -f "/app/config/monitor.json" ]; then
        log_error "健康检查失败: 配置文件不存在"
        return 1
    fi
    
    log_info "健康检查通过"
    return 0
}

# 启动监控服务
start_monitor() {
    local mode="${MONITOR_MODE:-server}"
    
    log_info "启动监控服务 (模式: $mode)..."
    
    case "$mode" in
        "server")
            exec python -m monitor.server_monitor --config /app/config/monitor.json
            ;;
        "memory")
            exec python -m monitor.memory_monitor --config /app/config/monitor.json
            ;;
        "both")
            # 启动两个监控服务
            python -m monitor.memory_monitor --config /app/config/monitor.json &
            exec python -m monitor.server_monitor --config /app/config/monitor.json
            ;;
        *)
            log_error "未知的监控模式: $mode"
            exit 1
            ;;
    esac
}

# 信号处理
cleanup() {
    log_info "接收到停止信号，正在清理..."
    
    # 停止后台进程
    jobs -p | xargs -r kill
    
    log_info "清理完成，退出"
    exit 0
}

# 注册信号处理器
trap cleanup SIGTERM SIGINT

# 主函数
main() {
    show_banner
    check_environment
    create_directories
    generate_config
    check_dependencies
    wait_for_services
    
    # 如果是健康检查模式
    if [ "$1" = "health-check" ]; then
        health_check
        exit $?
    fi
    
    # 如果指定了自定义命令
    if [ $# -gt 0 ] && [ "$1" != "start" ]; then
        log_info "执行自定义命令: $*"
        exec "$@"
    fi
    
    # 启动监控服务
    start_monitor
}

# 执行主函数
main "$@"